package com.easy.util;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class EmailUtil {

    private static final String FROM = "2319747729@qq.com";
    private static final String AUTH_CODE = "mlnkkcwvapktdibc";
    private static final String HOST = "smtp.qq.com";
    private static final String PORT = "465";

    // 验证码有效期（分钟）
    private static final int CODE_EXPIRATION_MINUTES = 5;

    private static final Session session;

    // 存储验证码信息（邮箱 -> 验证码+时间戳）
    public static final Map<String, VerificationCode> emailCodeMap = new ConcurrentHashMap<>();

    // 定时清理任务
    private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    static {
        Properties props = new Properties();
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, AUTH_CODE);
            }
        });

        // 启动定时清理任务，每分钟检查一次过期验证码
        scheduler.scheduleAtFixedRate(EmailUtil::cleanExpiredCodes, 1, 1, TimeUnit.MINUTES);
    }

    public static void sendEmail(String to, String text) {
        Message message = new MimeMessage(session);
        try {
            message.addFrom(new Address[]{new InternetAddress(FROM)});
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("验证码");
            message.setContent("<h1 style='color:red'>尚品验证码:" + text + "</h1>", "text/html;charset=utf-8");
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取验证码
     * @param email 邮箱
     * @return 验证码，如果不存在或已过期则返回null
     */
    public static String getCode(String email) {
        VerificationCode codeInfo = emailCodeMap.get(email);
        if (codeInfo == null) {
            return null;
        }

        // 检查是否过期
        if (System.currentTimeMillis() - codeInfo.timestamp > TimeUnit.MINUTES.toMillis(CODE_EXPIRATION_MINUTES)) {
            // 过期则删除
            emailCodeMap.remove(email);
            return null;
        }

        return codeInfo.code;
    }

    /**
     * 设置验证码
     * @param email 邮箱
     * @param code 验证码
     */
    public static void setCode(String email, String code) {
        emailCodeMap.put(email, new VerificationCode(code, System.currentTimeMillis()));
    }

    /**
     * 删除验证码
     * @param email 邮箱
     */
    public static void removeCode(String email) {
        emailCodeMap.remove(email);
    }

    /**
     * 清理过期验证码
     */
    private static void cleanExpiredCodes() {
        long currentTime = System.currentTimeMillis();
        long expirationTime = TimeUnit.MINUTES.toMillis(CODE_EXPIRATION_MINUTES);

        Iterator<Map.Entry<String, VerificationCode>> iterator = emailCodeMap.entrySet().iterator();
        int removedCount = 0;

        while (iterator.hasNext()) {
            Map.Entry<String, VerificationCode> entry = iterator.next();
            VerificationCode codeInfo = entry.getValue();

            if (currentTime - codeInfo.timestamp > expirationTime) {
                iterator.remove();
                removedCount++;
            }
        }

        if (removedCount > 0) {
            System.out.println("清理了 " + removedCount + " 个过期验证码");
        }
    }

    /**
     * 获取当前存储的验证码数量
     * @return 验证码数量
     */
    public static int getCodeCount() {
        return emailCodeMap.size();
    }

    /**
     * 关闭定时清理任务
     */
    public static void shutdown() {
        scheduler.shutdown();
    }

    /**
     * 验证码信息类（包含验证码和时间戳）
     */
    private static class VerificationCode {
        final String code;
        final long timestamp;

        VerificationCode(String code, long timestamp) {
            this.code = code;
            this.timestamp = timestamp;
        }
    }

/*    public static void main(String[] args) {
        EmailUtil.sendEmail("2319747729@qq.com", "123456");
    }*/
}
